﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace CLFramework.Text
{
    public class MessageBodyFactory
    {
       
        static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static string GetMessageBody<T>(T source, string templeteContent)
        {
            List<string> replaceStr = GetReplaceStr(templeteContent);

            foreach (string replaceName in replaceStr)
            {
                object ob = null;
                try
                {
                     ob = EmitHelper.GetPropertyValue<T>(source, GetFeildName(replaceName));
                }
                catch (Exception e)
                {
                    Logger.Error("there is no cloumn " + replaceName,e);
                }
               // string replaceValue = ob == null ? replaceName : ob.ToString();

                //modidy at 20110818 内容为空时,不显示字段名,显示空

                string replaceValue = ob == null ? "" : ob.ToString();

                templeteContent = templeteContent.Replace(replaceName, replaceValue);
            } 

            return templeteContent; 
        }

        private static List<string> GetReplaceStr(string templeteConent)
        {
            Regex rg = new Regex(@"(?i)(\[[A-Za-z0-9_]+.[A-Za-z0-9_]+\])");
            MatchCollection matchs = rg.Matches(templeteConent);
            List<string> result = new List<string>();

            foreach (Match m in matchs)
            {
                string value = m.Groups[0].Value;

                if (!result.Contains(value))
                {
                    result.Add(value);
                }
            }
            return result;
        }
         
        private static string GetFeildName(string ReplaceStr)
        {
            string[] feilds = ReplaceStr.Split('.');

            if (feilds.Length > 1)
            {
                return feilds[1].TrimEnd(']');
            }
            else
            {
                return feilds[0].TrimStart('[').TrimEnd(']');
            }
        }
    }
}
